//
//  SubjectVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/18.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "SubjectVC.h"
#import "SubjectCell.h"
#import "SubjectModal.h"
#import <AFHTTPSessionManager.h>
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "SubjectDetailPageVC.h"
#import <MJRefresh.h>
@interface SubjectVC () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableview;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger number; /**< 用来保存加载新数据的动态值 */
@end

@implementation SubjectVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // navigation
    self.navigationItem.title = @"专题";

    // 处理数据
    [self dataHandler];
    // 创建视图
    [self createSubviews];
    // 导航栏隐藏
    [self hidden];
    // 给加载新数据的动态值赋初值
    self.number = 2;
    // 下拉刷新
    [self refresh];
}

/// 数据处理
- (void)dataHandler
{
    NSString *urlStr = @"http://appapi.17house.com/xiaoguotuApi.php?action=albumList&page=1&pageSize=10&tagid=1";
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功~~");
        NSMutableArray *arr = responseObject[@"data"];
        self.dataArr = [SubjectModal modelHanderWithArray:arr];
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
    }];
    
    //下拉刷新结束
    [self.tableview.mj_header endRefreshing];
}

/// 创建视图
- (void)createSubviews
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    
    [_tableview registerClass:[SubjectCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableview];
    [_tableview release];
}

/// 设置cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

/// 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SubjectCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        SubjectModal *m = _dataArr[indexPath.row];
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:m.url]];
        cell.contentLabel.text = m.desc;
        cell.likeImg.image = [UIImage imageNamed:@"huiaixin@2x"];
        cell.likeLabel.text = m.like_num;
        cell.commentImg.image = [UIImage imageNamed:@"huicomment@2x"];
        cell.commentLabel.text = m.comment_count;
        return cell;
    }else{
        return cell;
    }
}

/// 设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 2.5;
}

/// 点击cell进入详情页
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SubjectDetailPageVC *detailVC = [[SubjectDetailPageVC alloc] init];
    SubjectModal *m = _dataArr[indexPath.row];
    detailVC.idStr = m.detailId;
    [self.navigationController pushViewController:detailVC animated:YES];
}



- (void)hidden
{
    // 导航栏隐藏设置
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        // 取消ScrollView的内容自动调整
        self.automaticallyAdjustsScrollViewInsets = NO;
        //tableView边界预留
        UIEdgeInsets insets = self.tableview.contentInset;
        // 让上边界的预留值和导航栏相等
        insets.top = self.navigationController.navigationBar.bounds.size.height;
        //把修改后的边界预留值赋给tableView
        self.tableview.contentInset = insets;
        // 滚动指标点到滚到视图的边缘的距离
        self.tableview.scrollIndicatorInsets = insets;
    }
}

// 导航栏滚动
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}

// 下拉刷新 上拉加载
- (void)refresh
{
    //下拉刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [self.tableview.mj_header beginRefreshing];
    
    //上拉加载
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //判断 如果保存数据的数组不为空就开始加载新的数据
    if (_dataArr.count != 0) {
        [self.tableview.mj_footer beginRefreshing];
    }
}

- (void)loadNewData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://appapi.17house.com/xiaoguotuApi.php?action=albumList&page=%ld&pageSize=10&tagid=1",self.number];
    [[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"专题加载成功");
        // 创建数组保存新请求的数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [SubjectModal modelHanderWithArray:responseObject[@"data"]];
        //将新的数据依次加入到数据数组里面
        for (NSInteger i = 0; i < 10; i++) {
            [_dataArr addObject:newDataArr[i]];
        }
        //刷新tableView
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"专题加载失败");
    }];
    
    //结束刷新
    [self.tableview.mj_footer endRefreshing];
    // 动态值加一
    self.number += 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
